package cn.wolfcode.luowowo.service.impl;

import cn.wolfcode.luowowo.domain.Destination;
import cn.wolfcode.luowowo.domain.Region;
import cn.wolfcode.luowowo.query.RegionQuery;
import cn.wolfcode.luowowo.repository.RegionRepository;
import cn.wolfcode.luowowo.service.IRegionService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.domain.*;
import org.springframework.data.mongodb.core.MongoTemplate;
import org.springframework.data.mongodb.core.query.Query;
import org.springframework.stereotype.Service;

import java.util.List;
import java.util.Optional;

@Service
public class RegionServiceImpl implements IRegionService {


    @Autowired
    private RegionRepository regionRepository;


    @Autowired
    private MongoTemplate mongoTemplate;


    @Override
    public void save(Region region) {
        region.setId(null);
        regionRepository.save(region);
    }

    @Override
    public void update(Region region) {

        regionRepository.save(region);
    }

    @Override
    public void delete(String id) {
        regionRepository.deleteById(id);

    }

    @Override
    public Region get(String id) {
        Optional<Region> op = regionRepository.findById(id);
        if (op.isPresent()){
            Region region = op.get();
            return region;
        }
        return null;
    }

    @Override
    public List<Region> list()
    {
        return regionRepository.findAll();
    }

    // 分页操作
    @Override
    public Page<Region> query(RegionQuery qo) {

        Query query = new Query();
        // 查询总页数
        long count = mongoTemplate.count(query, Region.class);
        if (count == 0){
            return Page.empty();
        }

        // 分页排序
        Pageable pageable = PageRequest.of(qo.getCurrentPage() - 1, qo.getPageSize(), Sort.Direction.ASC, "_id");

        query.with(pageable);

        List<Region> list = mongoTemplate.find(query, Region.class);


        return new PageImpl<>(list,pageable,count);

    }

    /**
     * 热门区域展示
     * @return
     */
    @Override
    public List<Region> queryHotRegion() {
        // 热门的且按照等级排序(条件就是Region.STATE_HOT = 1)
        List<Region> regions = regionRepository.findByIshotOrderBySequenceAsc(Region.STATE_HOT);
        return regions;
    }



}
